<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useUserStore } from '@/stores/useUserStore'
import api from '@/api/request'
import { ElMessage } from 'element-plus'
import { ChatRound } from '@element-plus/icons-vue'

const userStore = useUserStore()
const teamMembers = ref([])
const messages = ref({})
const unreadCounts = ref({})
const newMessage = ref('')
const selectedMember = ref(null)
const wsConnection = ref(null)
const isConnected = ref(false)

// 获取团队成员列表
const fetchTeamMembers = async () => {
  try {
    const response = await api.post('/allteammer')
    if (response.data && Array.isArray(response.data.data)) {
      teamMembers.value = response.data.data.filter(
        (member) => member.id !== userStore.userId
      )
      // 初始化每个用户的聊天记录和未读消息数
      teamMembers.value.forEach((member) => {
        messages.value[member.id] = []
        unreadCounts.value[member.id] = 0
      })
    }
  } catch (error) {
    console.error('获取团队成员失败:', error)
    ElMessage.error('获取团队成员失败')
  }
}

// 建立WebSocket连接
const connectWebSocket = () => {
  // 确保没有旧的连接
  if (wsConnection.value) {
    wsConnection.value.close() // 如果已经有连接，先关闭它
  }

  const wsUrl = `ws://xvr8a0okpffe-7095.beijing-01.dayunet.com/ws?userId=${userStore.userId}`
  wsConnection.value = new WebSocket(wsUrl)

  // 确保 wsConnection.value 被正确初始化后才设置事件
  wsConnection.value.onopen = () => {
    console.log('WebSocket连接成功')
    isConnected.value = true
    ElMessage.success('已连接到聊天服务器')
  }

  wsConnection.value.onmessage = (event) => {
    try {
      const data = JSON.parse(event.data)
      console.log('收到新消息:', data)

      // 只处理senderType为"user"的消息
      if (data.senderType === 'user') {
        // 确保发送者ID在消息对象中存在
        if (!messages.value[data.fromUserId]) {
          messages.value[data.fromUserId] = []
          unreadCounts.value[data.fromUserId] = 0
        }

        // 添加新消息到对应用户的聊天记录
        messages.value[data.fromUserId].push({
          fromUserId: data.fromUserId,
          content: data.content,
          timestamp: new Date().toISOString()
        })

        // 如果当前没有选中该用户，增加未读消息数
        if (selectedMember.value?.id !== data.fromUserId) {
          unreadCounts.value[data.fromUserId] =
            (unreadCounts.value[data.fromUserId] || 0) + 1
          const sender = teamMembers.value.find((m) => m.id === data.fromUserId)
          if (sender) {
            ElMessage(`收到来自 ${sender.username} 的新消息`)
          }
        }
      } else {
        // 忽略非用户消息
        console.log('忽略消息：非用户发送的消息', data)
      }
    } catch (error) {
      console.error('处理消息失败:', error)
    }
  }

  // 在确保 WebSocket 已初始化之后，才设置 onclose 事件
  if (wsConnection.value) {
    wsConnection.value.onclose = () => {
      console.log('WebSocket连接关闭')
      isConnected.value = false
      ElMessage.warning('聊天服务器连接已断开')
    }
  }

  wsConnection.value.onerror = (error) => {
    console.error('WebSocket错误:', error)
    ElMessage.error('聊天服务器连接错误')
  }
}

// 选择聊天对象
const selectMember = (member) => {
  selectedMember.value = member
  // 重置该用户的未读消息数
  unreadCounts.value[member.id] = 0
}

// 发送消息
const sendMessage = async () => {
  if (!newMessage.value.trim() || !selectedMember.value) return

  try {
    const messageData = {
      fromUserId: userStore.userId,
      toUserId: selectedMember.value.id,
      content: newMessage.value
    }

    // 确保当前用户的聊天记录存在
    if (!messages.value[selectedMember.value.id]) {
      messages.value[selectedMember.value.id] = []
    }

    // 添加到本地消息列表
    messages.value[selectedMember.value.id].push({
      fromUserId: userStore.userId,
      content: newMessage.value,
      timestamp: new Date().toISOString()
    })

    // 发送到服务器
    const response = await api.post('/chat', messageData)

    if (response.data.code === 200) {
      newMessage.value = '' // 清空输入框
      console.log('消息发送成功:', response.data)
    } else {
      ElMessage.error('发送失败：' + response.data.message)
    }
  } catch (error) {
    console.error('发送消息失败:', error)
    ElMessage.error('发送消息失败')
  }
}
// 获取用户ID
const getId = async () => {
  try {
    const response = await api.post('/id')
    console.log('response', response)

    userStore.userId = response.data.data
  } catch (error) {
    console.error('获取用户ID失败:', error)
    ElMessage.error('获取用户ID失败')
  }
}

onMounted(async () => {
  await getId()
  fetchTeamMembers()
  connectWebSocket()
})

// 组件卸载时关闭WebSocket连接
onUnmounted(() => {
  if (wsConnection.value) {
    wsConnection.value.close()
  }
})
</script>

<template>
  <div class="chat-container">
    <!-- 联系人列表 -->
    <div class="contacts-list">
      <div class="contacts-header">
        <h3>联系人列表</h3>
      </div>
      <div class="contacts-body">
        <div
          v-for="member in teamMembers"
          :key="member.id"
          class="contact-item"
          :class="{ active: selectedMember?.id === member.id }"
          @click="selectMember(member)"
        >
          <el-avatar :size="40" class="contact-avatar">
            {{ member.username.charAt(0).toUpperCase() }}
          </el-avatar>
          <div class="contact-info">
            <div class="contact-name">{{ member.username }}</div>
          </div>
          <!-- 添加未读消息数量提示 -->
          <div v-if="unreadCounts[member.id] > 0" class="unread-badge">
            {{ unreadCounts[member.id] > 99 ? '99+' : unreadCounts[member.id] }}
          </div>
        </div>
      </div>
    </div>

    <!-- 聊天区域 -->
    <div class="chat-area">
      <div v-if="selectedMember" class="chat-header">
        <h3>{{ selectedMember.username }}</h3>
      </div>
      <div v-else class="chat-placeholder">
        <el-icon :size="64" class="placeholder-icon"><ChatRound /></el-icon>
        <p>选择一个联系人开始聊天</p>
      </div>

      <template v-if="selectedMember">
        <div class="messages-container">
          <div
            v-for="(message, index) in messages[selectedMember.id]"
            :key="index"
            class="message"
            :class="{
              'message-sent': message.fromUserId === userStore.userId,
              'message-received': message.fromUserId !== userStore.userId
            }"
          >
            <div class="message-content">
              {{ message.content }}
            </div>
            <div class="message-time">
              {{ new Date(message.timestamp).toLocaleTimeString() }}
            </div>
          </div>
        </div>

        <div class="chat-input">
          <el-input
            v-model="newMessage"
            type="text"
            placeholder="输入消息..."
            @keyup.enter="sendMessage"
            :disabled="!selectedMember"
          >
            <template #append>
              <el-button
                @click="sendMessage"
                type="primary"
                :disabled="!selectedMember"
              >
                发送
              </el-button>
            </template>
          </el-input>
        </div>
      </template>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.chat-container {
  display: flex;
  height: calc(100vh - 120px);
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  margin: 20px;
  overflow: hidden;
}

.contacts-list {
  width: 280px;
  border-right: 1px solid #e6e6e6;
  display: flex;
  flex-direction: column;

  .contacts-header {
    padding: 20px;
    border-bottom: 1px solid #e6e6e6;

    h3 {
      margin: 0;
      color: #333;
      font-size: 16px;
    }
  }

  .contacts-body {
    flex: 1;
    overflow-y: auto;
  }
}

.contact-item {
  display: flex;
  align-items: center;
  padding: 12px 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;

  &:hover {
    background-color: #f5f7fa;
  }

  &.active {
    background-color: #ecf5ff;
  }

  .contact-avatar {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    margin-right: 12px;
  }

  .contact-info {
    flex: 1;

    .contact-name {
      font-size: 14px;
      color: #333;
      margin-bottom: 4px;
    }
  }

  .unread-badge {
    position: absolute;
    top: 8px;
    right: 8px;
    background: #f56c6c;
    color: white;
    font-size: 12px;
    min-width: 20px;
    height: 20px;
    line-height: 20px;
    text-align: center;
    border-radius: 10px;
    padding: 0 6px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }
}

.chat-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #f5f7fa;

  .chat-header {
    padding: 20px;
    background: #fff;
    border-bottom: 1px solid #e6e6e6;

    h3 {
      margin: 0;
      color: #333;
      font-size: 16px;
    }
  }

  .chat-placeholder {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    color: #909399;

    .placeholder-icon {
      margin-bottom: 16px;
      color: #dcdfe6;
    }

    p {
      font-size: 14px;
    }
  }
}

.messages-container {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
}

.message {
  max-width: 70%;
  margin-bottom: 16px;
  display: flex;
  flex-direction: column;

  .message-content {
    padding: 12px 16px;
    border-radius: 8px;
    font-size: 14px;
    line-height: 1.5;
    word-break: break-word;
  }

  .message-time {
    font-size: 12px;
    color: #909399;
    margin-top: 4px;
  }

  &.message-sent {
    align-self: flex-end;

    .message-content {
      background: #409eff;
      color: #fff;
      border-bottom-right-radius: 2px;
    }

    .message-time {
      text-align: right;
    }
  }

  &.message-received {
    align-self: flex-start;

    .message-content {
      background: #fff;
      color: #333;
      border-bottom-left-radius: 2px;
    }
  }
}

.chat-input {
  padding: 20px;
  background: #fff;
  border-top: 1px solid #e6e6e6;

  :deep(.el-input-group__append) {
    padding: 0;

    .el-button {
      margin: 0;
      border: none;
      height: 32px;
      padding: 0 16px;
    }
  }
}
</style>
